<%@page import="entity.Admin"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
Admin admin = (Admin) session.getAttribute("admin");
String deptName = "";
if("部门".equals(admin.getIsSuper())) {
	deptName = admin.getDeptName();
}
%>

<div class="callout callout-left">
  <span class="callout-title text-muted">用户许可审批</span><!-- &nbsp;<span class="glyphicon glyphicon-question-sign"></span> -->
</div>

<div class="callout">
  <form class="form-inline" action="" method="post">
  <div class="form-group">
    <label for="userName_search">姓名：</label>
    <input type="text" class="form-control" id="userName_search" name="userName_search" placeholder="用户账号"  autocomplete="off" />
  </div>
  <div class="form-group">
    <label for="deptName_search">所属部门：</label>
    <select class="form-control" name="deptName_search" id="deptName_search">
      <option value="">--全部--</option>
    </select>
  </div>
  <div class="form-group">
    <label for="softName_search">商品：</label>
    <select class="form-control" name="softName_search" id="softName_search">
      <option value="">--全部--</option>
    </select>
  </div>
  <div class="form-group">
    <label for="status_search">状态：</label>
    <select class="form-control" name="status_search" id="status_search">
      <option value="">--全部--</option>
      <option value="已通过">已通过</option>
      <option value="待审批">待审批</option>
      <option value="已拒绝">已拒绝</option>
    </select>
  </div>&nbsp;&nbsp;
  <a class="btn btn-primary" id="doSearch"><span class="glyphicon glyphicon-search">&nbsp;搜索</span></a>
  <!-- &nbsp;&nbsp;&nbsp;<a class="btn btn-info"><span class="glyphicon glyphicon-remove-circle">&nbsp;清除</span></a> -->
</form>
</div>

<div class="callout callout-white">
<div class="table-responsive">
  <table class="table table-hover">
    <thead>
      <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>用户所在部门</th>
        <th>软件名称</th>
        <th>请求时间</th>
        <th>请求理由</th>
        <th>请求数量</th>
        <th>批准数量</th>
        <th>批准日期</th>
        <th>批准管理员</th>
        <th>批准状态</th>
        <th>动作</th>
      </tr>
    </thead>
    <tbody id="ulreq_content">
    </tbody>
  </table>
  </div>
</div>

<script>
require.config({
	paths: {
		jquery: 'jquery-1.9.1.min',
		commmon: 'common',
		bootstrapswitch: 'bootstrap-switch.min'
	}
});
require(['jquery', 'common'], function($, common) {

var workspace = function() {

	var domKey;
	var dataOpt;
	var userLicenseReqs;
	var softwares;
	var departments;
	var deptLicense;

	var init = function() {
		domKey = common.commData.domKey;
		dataOpt = common.dataOpt;

    deptLicense = common.ajaxLoadData(dataOpt.deptLicenseOpt);
		softwares = common.ajaxLoadData(dataOpt.softwareOpt);
		departments = common.ajaxLoadData(dataOpt.departmentOpt);
		dataOpt.userLicenseReqOpt.data = {"deptName":encodeURI(encodeURI("<%=deptName %>"))}

		_initTable();
		_searchActive();
	}

	// 初始化表格
	var _initTable = function() {

		userLicenseReqs = common.ajaxLoadData(dataOpt.userLicenseReqOpt);
    dataOpt.userLicenseReqOpt.data = {"deptName":encodeURI(encodeURI("<%=deptName %>"))}

		var template = "<tr><th>#row#</th>" +
			"<td>#userName#</td>" +
			"<td>#deptName#</td>" +
			"<td>#softName#</td>" +
			"<td>#reqDate#</td>" +
			"<td>#reason#</td>" +
			"<td>#reqQuantity#</td>" +
			"<td>#assignNum#</td>" +
			"<td>#assignDate#</td>" +
			"<td>#adminName#</td>" +
			"<td><span name='statustext'>#status#</div></td>" +
			"<td>" +
      "<a href='#myModal' data-toggle='modal' class='approve' data-id='#reqId#' data-max='#reqQuantity#' data-assign='#assignNum#'" +
      " data-status='#status#' data-ds='#deptName#-#softName#'>" +
      "<span class='glyphicon glyphicon-edit text-primary'>审批</span></a>&nbsp;" +
      "<a href='#myModal' data-toggle='='modal' class='refuse' data-id='#reqId#' data-status='#status#'><span class='glyphicon glyphicon-remove-sign'>拒绝</span></a>" +
      "</td>" +
			"</tr>";

        var row = 0;
        var htmlArr = [];
		var thisT = "";
		var html = "";
		for(var i = 0, n = userLicenseReqs.length; i < n; i++) {
			thisT = template;
			thisT = thisT.replace(/#row#/g, ++row).replace(/#userName#/g, userLicenseReqs[i]["userName"]).replace(/#deptName#/g, userLicenseReqs[i]["deptName"])
				.replace(/#softName#/g, userLicenseReqs[i]["softName"]).replace(/#reqQuantity#/g, userLicenseReqs[i]["reqQuantity"]).replace(/#reqDate#/g, userLicenseReqs[i]["reqDate"])
				.replace(/#reason#/g, userLicenseReqs[i]["reason"]).replace(/#assignNum#/g, userLicenseReqs[i]["assignNum"]).replace(/#assignDate#/g, userLicenseReqs[i]["assignDate"])
				.replace(/#adminName#/g, userLicenseReqs[i]["adminName"]).replace(/#status#/g, userLicenseReqs[i]["status"]).replace(/#reqId#/g, userLicenseReqs[i]["reqId"]);
			html += thisT;
			if((row !== 0) && (row % common.commData.pageNum === 0)) {
        htmlArr.push(html);
        html = "";
      }
    }
    if("" !== html) {
        htmlArr.push(html);// 插入不满pageNum的几条数据
    }

    var opt = {
        htmlArr: htmlArr,
        content: $("#ulreq_content"),
      }
      common.pageNav(opt, function() {
          $("[name='statustext']").each(function() {
              if("待审批" == $(this).html()) {
                  $(this).addClass("text-warning");
              } else if("已通过" == $(this).html()) {
                  $(this).addClass("text-success");
              } else {
                  $(this).addClass("text-danger");
              }
          });

          refuse();
          approve();
      });
	}

	// 审批
	var approve = function() {
		var modalBodyTemplate = "<form class='form-horizontal' role='form'>" +
			/*"<div class='form-group'>" +
			"<label for='status' class='col-sm-4 control-label'>状态</label>" +
			"<div class='col-sm-8'>" +
			"<select class='form-control' name='status' id='status'>" +
			"<option value='待审批'>待审批</option>" +
			"<option value='已通过'>通过</option>" +
			"<option value='已拒绝'>拒绝</option>" +
			"</select></div></div>" +
			"<div class='form-group'>" +
			"<label for='createdate' class='col-sm-3 control-label'>密钥</label>" +
			"<div class='col-sm-9'>" +
			"<select class='form-control' name='' id=''>" +
			"<option value=''></option>" +
			"</select></div></div>" + */
			"<div class='form-group'>" +
			"<label for='assignNum' class='col-sm-4 control-label'>分配数量</label>" +
			"<div class='col-sm-8'>" +
			"<input class='form-control' id='assignNum' name='assignNum' type='number' min='0'/>" +
            "<span id='helpBlock' class='help-block'></span>" +
			"</div></div></form>";

		$(".approve").each(function() {
			var reqId = $(this).data("id");
			var max = $(this).data("max");
			var assign = $(this).data("assign");
			var status = $(this).data("status");

			// 确认一个部门许可数量
      var ds = $(this).data("ds");

			if("待审批" === status) {
				$(this).click(function() {
					common.cleanModal();
					domKey.modal.find(".modal-dialog").addClass("modal-sm");
          domKey.modalLabel.html("批准数量");
          domKey.modalBody.html(modalBodyTemplate);

          $("#assignNum").attr({"max":max,"value":assign});

          // 部门剩余许可数量
          var licLeft;
          for(var i = 0, n = deptLicense.length; i < n; i++) {
              if(ds == deptLicense[i]["deptName"] + "-" +deptLicense[i]["softName"]) {
                  licLeft = deptLicense[i]["licenseNum"] - deptLicense[i]["activated"]
                  $("#helpBlock").text("剩余可分配许可数量：" + licLeft);
                  break;
              }
          }

          domKey.modalAct.html("保存")
          .on("click", function() {
            var data = {
              "adminName": "<%=admin.getAdminName() %>",
              "reqId": reqId,
              "status": "已通过",
              "assignNum": $("#assignNum").val()
            }
            if(data["assignNum"] > max) {
              alert("分配数量不能大于请求数量，请重新填写");
                        common.enable(domKey.modalAct);
            } else if(data["assignNum"] > licLeft) {
                        alert("超出部门剩余许可数量");
                        common.enable(domKey.modalAct);
            } else {
              $.ajax({
                url: "<%=path %>/servlet/user/EditAssignNumServlet",
                type: "post",
                data: data,
                dataType: "json",
                async: false,
                success: function(_json) {
                  if("1" == _json["retCode"]) {
                                        deptLicense = common.ajaxLoadData(dataOpt.deptLicenseOpt);
                  } else {
                    alert(_json["desc"]);
                  }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                  alert("EditAssignNumServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
                },
                complete: function() {
                  domKey.modal.find(".close").click();
                  _initTable();// 刷新表格
                }
              });
            }
          });
				});
			} else {
				$(this).addClass("a-disabled");
			}
		});
	}

	// 拒绝
  var refuse = function() {
      $(".refuse").each(function() {
          if("待审批" == $(this).data("status")) {
              $(this).click(function() {
                  var data = {
                      "adminName": "<%=admin.getAdminName() %>",
                      "reqId": $(this).data("id"),
                      "status": "已拒绝",
                      "assignNum": "0"
                  }
                  $.ajax({
                      url: "<%=path %>/servlet/user/EditAssignNumServlet",
                      type: "post",
                      data: data,
                      dataType: "json",
                      async: false,
                      success: function(_json) {
                          if("1" == _json["retCode"]) {
                              // deptLicense = common.ajaxLoadData(dataOpt.deptLicenseOpt);
                          } else {
                              alert(_json["desc"]);
                          }
                      },
                      error: function(XMLHttpRequest, textStatus, errorThrown) {
                          alert("EditAssignNumServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
                      },
                      complete: function() {
                          domKey.modal.find(".close").click();
                          _initTable();// 刷新表格
                      }
                  });
              });
          } else {
              $(this).addClass("a-disabled");
          }
      });
  }

	// 搜索功能
	var _searchActive = function() {

    if("<%=deptName %>" == "") {
      // 部门
      departments.forEach(function(dept) {
          var opt = document.createElement("option");
          $(opt).val(dept["deptName"]);
          $(opt).text(dept["deptName"]);
          $("#deptName_search").append(opt);
      });
    } else {
      var opt = document.createElement("option");
      $(opt).val("<%=deptName %>");
      $(opt).text("<%=deptName %>");
      $("#deptName_search").html(opt);
    }


		// 商品
    softwares.forEach(function(software) {
      var opt = document.createElement("option");
      $(opt).val(software["softName"]);
      $(opt).text(software["softName"]);
      $("#softName_search").append(opt);
    });

		$("#doSearch").click(function() {
			dataOpt.userLicenseReqOpt.data = {
        "deptName": encodeURI(encodeURI($("#deptName_search").val())),
				"userName": encodeURI(encodeURI($("#userName_search").val())),
				"softName": $("#softName_search").val(),
				"status": encodeURI(encodeURI($("#status_search").val()))
			}
			_initTable();
		});
	}

	return {
		init: init
	}
}();
	
$(function() { workspace.init(); });

});

requirejs.onError = function (err) {  
  console.error(err);
  if (err.requireType === 'timeout') {
    console.error('modules: ' + err.requireModules);
  }
  throw err;
}
</script>